package com.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class MyClient {

    @Value("${netty.port}")
    private int port;

    @Value("${netty.host}")
    private String host;

    private SocketChannel socketChannel;

    public void sendMsg(String msg){
        socketChannel.writeAndFlush(msg);
    }

    /**
     * 加载
     */
    @PostConstruct
    public void start() throws InterruptedException {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        // 客户端引导类
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                //异步的客户端 TCP Socket 连接
                .channel(NioSocketChannel.class)
                .remoteAddress(host,port)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                //也可以使用匿名类
                .handler(new MyClientInitializer());

        ChannelFuture channelFuture = bootstrap.connect();
            //客户端断线重连逻辑
        channelFuture.addListener((ChannelFutureListener) future1 -> {
            if (future1.isSuccess()) {
                log.info("连接Netty服务端成功");
            } else {
                log.info("连接失败，进行断线重连");
                future1.channel().eventLoop().schedule(() -> {
                    try {
                        start();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }, 20, TimeUnit.SECONDS);
            }
        });

        //接收来自channel数据
        socketChannel =(SocketChannel) channelFuture.channel();
    }
}
